package com.toune.movie.mvp.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jkb.slidemenu.SlideMenuLayout;
import com.siberiadante.customdialoglib.EnsureDialog;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.BaseActivity;
import com.toune.movie.base.BaseFragment;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.base.myview.DownLoadApkDialog;
import com.toune.movie.mvp.contract.MainContract;
import com.toune.movie.mvp.fragment.MovieFragment;
import com.toune.movie.mvp.fragment.MovieTvFragment;
import com.toune.movie.mvp.fragment.MovieVipFragment;
import com.toune.movie.mvp.fragment.MusicFragment;
import com.toune.movie.mvp.presenter.MainPresenter;
import com.toune.movie.vo.ShareVo;
import com.uuch.adlibrary.bean.AdInfo;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxAppTool;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.RxRunTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gdut.bsx.share2.ShareContentType;

/**
 * Created by Administrator on 2018/4/28.
 */

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar bottomNavigationBar;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.mine_avatar)
    ImageView mineAvatar;
    @BindView(R.id.mine_nick)
    TextView mineNick;
    @BindView(R.id.mine_avator_relative)
    RelativeLayout mineAvatorRelative;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.sign_content)
    RxRunTextView signContent;
    @BindView(R.id.mine_sign_relative)
    RelativeLayout mineSignRelative;
    @BindView(R.id.layout_left_menu)
    LinearLayout layoutLeftMenu;
    @BindView(R.id.sv_left_menu)
    ScrollView svLeftMenu;
    @BindView(R.id.mainSlideMenu)
    SlideMenuLayout mainSlideMenu;
    @BindView(R.id.view_history_ll)
    LinearLayout viewHistoryLl;
    @BindView(R.id.kuozhan_ll)
    LinearLayout kuozhanLl;
    @BindView(R.id.login_and_loginout_btn)
    Button loginAndLoginoutBtn;
    private List<BaseFragment> fragmentList = new ArrayList<>();
    private FragmentManager fragmentManager;

    public static MainActivity mainActivity;

    @Override // 实例化presenter
    public MainPresenter initPresenter() {
        return new MainPresenter();
    }

    @Override
    public void loadMore() {

    }

    @Override
    public void refreData() {

    }

    @Override
    public void init(Bundle savedInstanceState) {
        mainActivity = this;
        mainSlideMenu.setParallaxSwitch(false);
        mainSlideMenu.setContentToggle(true);
        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_UPDATE);
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        int netApkCode = Integer.parseInt(list.get(0).getString("versionCode"));
                        int localApkCode = RxAppTool.getAppVersionCode(context);
                        if (localApkCode < netApkCode) {
                            AVFile file = list.get(0).getAVFile("file");
                            getApk(file.getUrl());
                        }
                    }
                }
            }
        });
        AVQuery<AVObject> avQueryPhone = new AVQuery<>(AppConstant.TAB_PHONE);
        final String phoneId = RxDeviceTool.getUniqueSerialNumber();
        avQuery.whereMatches("phoneId", phoneId);
        avQueryPhone.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                boolean isHave = false;
                if (e == null) {
                    if (list != null) {
                        if (list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                AVObject avObject = list.get(i);
                                String phoneId1 = avObject.getString("phoneId");
                                if (phoneId.equals(phoneId1)) {
                                    isHave = true;
                                    AppConstant.ISVIDEO = avObject.getInt("isVideo");
                                    AppConstant.ISFILE = avObject.getInt("isFile");
                                    AppConstant.ISPHONE = avObject.getInt("isPhone");
                                }
                            }
                        }
                    }
                }
                if (!isHave) {
                    AVObject avObject = new AVObject(AppConstant.TAB_PHONE);
                    avObject.put("phoneId", phoneId);
                    avObject.put("isVideo", 0);
                    avObject.put("isFile", 1);
                    avObject.put("isPhone", 1);
                    avObject.saveInBackground();
                }
            }
        });
        fragmentManager = getSupportFragmentManager();
        fragmentList.add(MovieFragment.newInstance());
//        fragmentList.add(MovieTvFragment.newInstance());
        fragmentList.add(MovieVipFragment.newInstance());
        fragmentList.add(MusicFragment.newInstance());
        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.mipmap.movie, "影视"))
//                .addItem(new BottomNavigationItem(R.mipmap.main_tv, "直播"))
                .addItem(new BottomNavigationItem(R.mipmap.main_vip, "VIP"))
                .addItem(new BottomNavigationItem(R.mipmap.music, "音乐"))
                .initialise();
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
        viewPager.setOffscreenPageLimit(5);
        viewPager.setAdapter(new MyPageAdapter(fragmentManager));
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                bottomNavigationBar.selectTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void updateView() {
        if (AVUser.getCurrentUser() == null) {
            loginAndLoginoutBtn.setText("登录");
            mineAvatar.setImageResource(R.mipmap.personal);
            mineNick.setText("我是昵称");
            signContent.setText("做自己人生的CEO");
        } else {
            loginAndLoginoutBtn.setText("退出");
            if (AVUser.getCurrentUser().getAVFile("image") != null) {
                String imagUrl = AVUser.getCurrentUser().getAVFile("image").getUrl();
                Glide.with(context).load(imagUrl).apply(new RequestOptions().circleCrop()).into(mineAvatar);
            }
            mineNick.setText(AVUser.getCurrentUser().getString("nick"));
            signContent.setText(AVUser.getCurrentUser().getString("sign"));
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected String getTitleStr() {
        return "";
    }

    @Override
    protected void initEventAndData() {
        MyUtil.showADDialog(context);
    }

    @Override
    public void method() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    @OnClick({R.id.red_package_ll, R.id.call_me_ll, R.id.mine_avator_relative, R.id.mine_sign_relative, R.id.view_history_ll, R.id.kuozhan_ll, R.id.login_and_loginout_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.red_package_ll:
//                AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_SHOP);
//                avQuery.whereMatches("tag", "1");
//                avQuery.findInBackground(new FindCallback<AVObject>() {
//                    @Override
//                    public void done(List<AVObject> list, AVException e) {
//                        if (e == null) {
//                            if (list.size() > 0) {
//                                Intent intentShare = new Intent();
//                                intentShare.setAction("Android.intent.action.VIEW");
//                                Uri uri = Uri.parse(list.get(0).getString("url")); // 商品地址
//                                intentShare.setData(uri);
//                                intentShare.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
//                                context.startActivity(intentShare);
//                            } else {
//                                RxToast.info("功能已下架");
//                            }
//                        }
//                    }
//                });
                MyUtil.showADDialog(context);
                break;
            case R.id.call_me_ll:
                if (MyUtil.checkApkExist(context, "com.tencent.mobileqq")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + 546554574 + "&version=1")));
                } else {
                    RxToast.info("本机未安装QQ应用");
                }
                break;
            case R.id.mine_avator_relative:
                if (AVUser.getCurrentUser() != null) {
                    RxActivityTool.skipActivity(context, MyDataActivity.class);
                }
                break;
            case R.id.mine_sign_relative:
                break;
            case R.id.view_history_ll:
                RxActivityTool.skipActivity(context, HistoryActivity.class);
                break;
            case R.id.kuozhan_ll:
                for (int i = 0; i < MyUtil.advList.size(); i++) {
                    if ("app".equals(MyUtil.advList.get(i).getString("to"))) {

                    }
                }
                AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_AD);
                avQuery.whereMatches("to", "app");
                avQuery.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(List<AVObject> list, AVException e) {
                        if (e == null) {
                            if (list.size() > 0) {
                                ShareVo shareVo = new ShareVo();
                                shareVo.setImagUrl(list.get(0).getAVFile("file").getUrl());
                                shareVo.setFileName("红酒，电影，音乐，咖啡");
                                shareVo.setTitle("糖泥影院");
                                shareVo.setUrl(list.get(0).getString("content"));
                                shareVo.setShareType(ShareContentType.IMAGE);
                                MyUtil.showShareDialog(context, shareVo);
                            }
                        }
                    }
                });
                break;
            case R.id.login_and_loginout_btn:
                if (AVUser.getCurrentUser() == null) {
                    RxActivityTool.skipActivity(context, LoginActivity2.class);
                } else {
                    AVUser.logOut();
                }
                updateView();
                break;
        }
    }

    private class MyPageAdapter extends FragmentStatePagerAdapter {

        public MyPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }


    private void getApk(final String url) {

        final EnsureDialog ensureDialog = new EnsureDialog(context).builder();
        ensureDialog.setPositiveButton("更新", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ensureDialog.dismiss();
                DownLoadApkDialog downLoadApkDialog = new DownLoadApkDialog(context, url);
                downLoadApkDialog.show();
                downLoadApkDialog.setCanceledOnTouchOutside(false);
            }
        }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ensureDialog.dismiss();
            }
        }).setTitle("发现新版本，是否现在更新")
                .show();
    }

    public void showMenu() {
        if (mainSlideMenu.isLeftSlideOpen()) {
            mainSlideMenu.closeLeftSlide();
        } else {
            mainSlideMenu.openLeftSlide();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateView();
    }
}
